package com.lcq.springbootcreate.project.ExceptionAndEnum;

import com.lcq.springbootcreate.project.common.ApiRestResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

// @ControllerAdvice 用与拦截异常
@ControllerAdvice
public class GlobalExceptionHandler {
    // 应该打上日志


    // @ExceptionHandler(Exception.class) 表示处理的异常类型
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handException(Exception e) {
        System.out.println(e.fillInStackTrace());
        return ApiRestResponse.error(MallExceptionEnum.SYS_ERROR);
    }

    // 处理业务异常
    @ExceptionHandler(MallException.class)
    @ResponseBody
    public Object handMallException(MallException e) {

        System.out.println(e.fillInStackTrace());
        return ApiRestResponse.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse handArgumentException(MethodArgumentNotValidException e) {
        return handBindingResult(e.getBindingResult());
    }

    private ApiRestResponse handBindingResult(BindingResult result) {
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError error : allErrors) {
                String message = error.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size() == 0) {
            return ApiRestResponse.error(MallExceptionEnum.ARGUMENT_WRONG);
        }
        return ApiRestResponse.error(MallExceptionEnum.ARGUMENT_WRONG.getCode(), list.toString());
    }

}
